package strategies;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

import strategies.Strategy;


/**
 * responsible  for dynamic loading
 * 
 * @author Vladimir Sarkisyan & Erez Levy
 *
 */
public class PluginChooser {
	private String strategyName;
	private String path;

	/**
	 * constructor
	 * @param strategyName - name of the class that will be loaded
	 * 
	 */
	public PluginChooser(String strategyName){
		try {
			//this.ReadFavoriteAlgo();
			
			//the strategyName algorithm
			this.strategyName = strategyName;
			
			//the path of the plugins 
            File f = new File("");
            path=new String(f.getAbsolutePath());
            //now path direct on directory plugins
            path = path + "\\bin\\";
            
            System.out.println("path: " + path);
		} catch (Exception e) {}

	}
	
	/**
	 * the function dynamicly load a class
	 * 
	 *  there is a classes the every class is plugin, the
	 *  function load the class and and take the instance of him - regular 
	 *  java file that implements a interface Strategy 
	 *  
	 * 
	 */
	public Strategy getStrategyInstanse() throws Exception  {
		//for debug 
		System.out.println("in PluginChooser - getStrategyInstanse");
		//
		// the path of the folder
		File f=new File(path);
		URL url;
		url = f.toURL();
		
		URL[] urls=new URL[]{url};
		// now it is create a class loader for this directory
		ClassLoader classLoader=new URLClassLoader(urls);
		System.out.println("after classLoader creation");
		System.out.println("strategyName: " + strategyName);
		// load the class of the Strategy - take according  to the strategyName
		Class<Strategy> classStrategy = (Class<Strategy>) classLoader.loadClass(strategyName);
		System.out.println("after get classStrategy");
		//create a instance of this class
		Strategy instance = classStrategy.newInstance();
		//set the strategy name
		instance.setStrategyName(strategyName);
		System.out.println("before return");
		return instance;
	}
}
